package com.yuchen.bearrecord.service.impl;

import com.yuchen.bearrecord.config.RequestHeaderContext;
import com.yuchen.bearrecord.config.Result;
import com.yuchen.bearrecord.dto.UserDto;
import com.yuchen.bearrecord.entity.Prescription;
import com.yuchen.bearrecord.entity.User;
import com.yuchen.bearrecord.repository.PrescriptionRepository;
import com.yuchen.bearrecord.repository.UserRepository;
import com.yuchen.bearrecord.service.PrescriptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class PrescriptionServiceImpl implements PrescriptionService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private PrescriptionRepository prescriptionRepository;

    @Override
    public Result getPrescriptions() {
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user = userRepository.findByOpenid(userDto.getOpenid());
        HashMap<Object, Object> map = new HashMap<>(1);
        List<Prescription> prescriptions = prescriptionRepository.findByUser(user);
        map.put("prescriptions", prescriptions);
        return Result.ok(map);
    }

    @Override
    public Result deletePrescription(Long pid) {
        try {
            prescriptionRepository.deleteByPid(pid);
        } catch (Exception e) {
            return Result.error("删除失败");
        }
        return Result.ok();
    }

    @Override
    public Result addPrescription(Prescription prescription) {
        if (!prescriptionRepository.findByName(prescription.getName()).isEmpty()) {
            return Result.error("医嘱名重复");
        }
        UserDto userDto = RequestHeaderContext.getInstance().getUserDto();
        User user = userRepository.findByOpenid(userDto.getOpenid());
        prescription.setUser(user);
        prescriptionRepository.saveAndFlush(prescription);
        return Result.ok();
    }

    @Override
    public Result updateRecent(Prescription prescription) {
        try {
            Prescription byPid = prescriptionRepository.findByPid(prescription.getPid());
            byPid.setRecent(prescription.getRecent());
            prescriptionRepository.save(byPid);
        } catch (Exception e) {
            return Result.error("修改失败");
        }
        return Result.ok();
    }
}
